﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace PositionSourceConfiguration
{
    public partial class CameraIntrinsicSettings : UserControl
    {
        private WebcamLEDPositionSourceConfiguration configuration;

        public WebcamLEDPositionSourceConfiguration WebcamPositionSourceConfiguration
        {
            get { return configuration; }
            set { configuration = value; }
        }

        public CameraIntrinsicSettings()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string filename = "intrinsic.txt";
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    filename = saveFileDialog.FileName;

                StreamWriter sw = new StreamWriter(filename);
                sw.WriteLine(tbFocus.Text);
                sw.WriteLine(tbDistortion.Text);
                sw.Close();
            }
            catch
            {
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            try
            {
                string filename = "intrinsic.txt";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                    filename = openFileDialog.FileName;

                StreamReader sr = new StreamReader(filename);
                tbFocus.Text = sr.ReadLine();
                tbDistortion.Text = sr.ReadLine();
                sr.Close();
                btnApply_Click(sender, e);
            }
            catch
            {
            }
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            if (configuration == null)
                return;
            string[] focus = tbFocus.Text.Split(';');

            double fx = Double.Parse(focus[0]);
            double fy = Double.Parse(focus[1]);
            double cx = Double.Parse(focus[2]);
            double cy = Double.Parse(focus[3]);

            string[] dist = tbDistortion.Text.Split(';');

            double[,] intrinsicMatrix = new double[3, 3] { { fx, 0, cx }, { 0, fy, cy }, { 0, 0, 1 } };

            double[,] distortionCoeffs = new double[1, 4] { { Double.Parse(dist[0]), Double.Parse(dist[1]), Double.Parse(dist[2]), Double.Parse(dist[3]) } };

            configuration.transformer.SetCameraParameters(intrinsicMatrix, distortionCoeffs);
        }

        private void btnSetOrigin_Click(object sender, EventArgs e)
        {
            if (configuration == null)
                return;
            configuration.SetReferenceTransformation();
        }
    }
}
